package org.woozoo.xhtml.speedtests
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.utils.getTimer;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.controls.RadioButtonGroup;
	import mx.managers.CursorManager;
	
	import org.woozoo.xhtml.core.API;
	import org.woozoo.xhtml.core.base.*;
	import org.woozoo.xhtml.speedtests.base.TestVO;
	
	/**
	 * @see http://www2.webkit.org/perf/slickspeed/
	 * */
	public class TestDocument
	{
		[Bindable] public var testResults : ArrayCollection;
		[Bindable] public var numTestPerSelector : int = 10;
		[Bindable] public var enableSelectorCache : Boolean = true;
		[Bindable] public var isTestRunning : Boolean = false;
		
		private var __view : TestView;
		private var __api : API;
		private var __testDocument : Document;
		private var __testIndex : int = -1;
		private var __enterFrameCounter : int = 0;
		
		
		public function TestDocument(view : TestView)
		{
			__view = view;
			__run();
		}
		
		private function __run() : void {
			__view.numTest.addEventListener(Event.CHANGE, __numTestChangeHandler);
			__view.start.addEventListener(MouseEvent.CLICK, __startClickHandler);
			__view.woozoxHome.addEventListener(MouseEvent.CLICK, __woozoxHomeClickHandler);
			__view.testSource.addEventListener(MouseEvent.CLICK, __testSourceClickHandler);
			__view.useCache.addEventListener(Event.CHANGE, __useCacheChangeHandler);
			
			__api = API.getInstance();
			__api.enableSelectorCache = enableSelectorCache;
			__api.startLoadingCallBack = __startLoading;
			__api.stopLoadingCallBack = __stopLoading;
			__api.setup('assets/xhtml/result.html', __resultSuccess, __resultError, 'result');
		}
		
		private function __numTestChangeHandler(e : Event) : void {
			numTestPerSelector = e.currentTarget.value;
		}
		
		private function __useCacheChangeHandler(e : Event) : void {
			enableSelectorCache = (e.currentTarget as RadioButtonGroup).selectedValue == 'yes';
			__api.enableSelectorCache = enableSelectorCache;
		}
		
		private function __startClickHandler(e : MouseEvent) : void {
			isTestRunning = !isTestRunning;
			if (isTestRunning) {
				__view.addEventListener(Event.ENTER_FRAME, __viewEnterFrameHandler);
			} else {
				__view.removeEventListener(Event.ENTER_FRAME, __viewEnterFrameHandler);
			}
		}
		
		private function __startLoading() : void {
			CursorManager.setBusyCursor();
		}
		
		private function __stopLoading() : void {
			CursorManager.removeBusyCursor();
		}
		
		private function __resultSuccess(document : Document) : void {
			__completeTestResults(document);
			__loadTest();
		}
		
		private function __loadTest() : void {
			__api.loadDocument(new Document('test', 'assets/xhtml/test-page.html'), __testSuccess, __testError);
		}
		
		private function __testSuccess(document : Document) : void {
			__testDocument = document;
		} 
		
		private function __viewEnterFrameHandler(e : Event) : void {
			__doTest();
		}
		
		private function __doTest() : void {
			__enterFrameCounter++;
			if (__enterFrameCounter % 10 != 0) {
				return;
			}
			__testIndex++;
			if (__testIndex >= testResults.length - 1 ) {
				isTestRunning = false;
				__view.removeEventListener(Event.ENTER_FRAME, __viewEnterFrameHandler);
			}
			
			var startTime : int = getTimer();
			var item : TestVO = testResults.getItemAt(__testIndex) as TestVO;
			var res : Array = [];
			for (var  i : int = 0; i < numTestPerSelector; i++) {
				res = __testDocument.querySelectorAll(item.selector);
			}
			item.woozox = (getTimer() - startTime) / numTestPerSelector;
			item.woozoxNumResults = res.length;
		} 
		
		private function __completeTestResults(document : Document) : void {
			var res : Array = [];
			
			var colums : Array = document.$$('#tbody tr');
			var len : int = colums.length;
			for (var i : int = 0; i < len; i++) {
				var item : Element = colums[i];
				var selector : Element = item.getElementsByClassName('selector')[0];
				var tests : Array = item.getElementsByClassName('test');
				
				var testVO : TestVO = new TestVO();
				testVO.selector = selector.innerHTML.replace('&gt;', '>');
				testVO.prototype = (tests[0] as Element).innerHTML.split(' ms')[0];
				testVO.jquery = (tests[1] as Element).innerHTML.split(' ms')[0];
				testVO.ext = (tests[2] as Element).innerHTML.split(' ms')[0];
				
				var split : Array = (tests[3] as Element).innerHTML.split(' ms | ');
				testVO.nativ = split[0];
				testVO.numResultsExpected = int((split[1] as String).replace(' found', ''));
				 
				res.push(testVO);
			}
			testResults = new ArrayCollection(res);
		}

		private function __resultError(reason : DocumentErrorReason, document : Document) : void {
			Alert.show('__resultError : '+reason.type);
		}
		private function __testError(reason : DocumentErrorReason, document : Document) : void {
			Alert.show('__testError : '+reason.type);
		}
		
		private function __woozoxHomeClickHandler(e : MouseEvent) : void {
			navigateToURL(new URLRequest('http://code.google.com/p/woozox/'));
		}
		
		private function __testSourceClickHandler(e : MouseEvent) : void {
			navigateToURL(new URLRequest('http://www2.webkit.org/perf/slickspeed/'));
		}
	}
}